﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using Bluebunnie.Library.Master.ProjectDataSetTableAdapters;
using Bluebunnie.Extensions;

namespace Bluebunnie.Library.Master
{
    /// <summary>
    /// Interaction logic for Users.xaml
    /// </summary>
    public partial class Users : PulseControl
    {
        tbl_userTableAdapter adapter = new tbl_userTableAdapter();
        tbl_permissionsTableAdapter permsAdapter = new tbl_permissionsTableAdapter();
        
        public Users()
        {
            InitializeComponent();

            Save = (sender, e) =>
            {
                ProjectDataSet dataset = (ProjectDataSet)FindResource("projectDataSet");
                adapter.Update(dataset.tbl_user);
            };

            try
            {
                Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Tidak dapat mengambil data. Pastikan server MySQL telah berjalan.\n\nError:\n{0}", ex.Message), "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        public override void Refresh()
        {
            base.Refresh();

            ProjectDataSet dataset = (ProjectDataSet)FindResource("projectDataSet");
            adapter.Fill(dataset.tbl_user);
            permsAdapter.Fill(dataset.tbl_permissions);

            CollectionViewSource source = (CollectionViewSource)FindResource("tbl_userViewSource");
            source.View.MoveCurrentToFirst();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            object userID = (sender as Button).CommandParameter;

            if (userID != null)
            {
                var passchange = new PasswordChanger() { Tag = userID };
                passchange.ShowDialog();
            }
            else
            {
                MessageBox.Show("Tidak dapat mengubah password user yang belum dimasukkan ke database. Silakan menekan tombol Save terlebih dahulu.", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }
    }
}
